package com.linefly.online_car;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.CoordinateConverter;
import com.amap.api.maps.MapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.Circle;
import com.amap.api.maps.model.CircleOptions;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.linefly.online_car.Custom.MyLoading;
import com.linefly.online_car.Custom.ReLogin;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import Been.Carsbeen;
import Socket.ExampleClient;
import Util.DateUtil;
import Util.JsonUtil;
import Util.NavigationBarUtil;
import Util.PreferenceUtil;
import okhttp3.Call;
import okhttp3.Response;

import static com.autonavi.amap.mapcore.maploader.NetworkState.isNetworkConnected;

public class MainActivity extends AppCompatActivity {
    private static final int LOCATION_CODE = 1;
    private LocationManager lm;//【位置管理】
    ///////////////////////////////////地图相关//////////////////////////
    MapView mMapView = null;
    AMap aMap;
    private UiSettings mUiSettings;//定义一个UiSettings对象
    private URI uri;

    private boolean isduanwangFlag = false;
    private boolean isyouwang = false;
    private ExampleClient exampleClient, duanwangClient;
    public List<Carsbeen> returnpoints = new ArrayList<>();
    public List<Carsbeen> acceptpoints = new ArrayList<>();
    private Carsbeen carsbeen;
    private static String carid = "no";//表示还没有marker被点击过
    private MarkerOptions markerOption;
    private LatLng latLng;
    private Map<String, Marker> idmarkerMap = new HashMap<>();
    private String fid = "", companyname = "", type = "";
    static MainActivity slideIns;
    private String chepai = "";
    private String token = "";

    private Context context;

    private DrawerLayout mDrawerLayout;
    private RelativeLayout left_drawerlayout;

    private View jianshi;
    private TextView tv_lng, tv_lat, tv_speed, tv_voltage, tv_carNumber, tv_time, tv_carid;
    private int flag_map_click = 0;//解决地图点击冲突
    private Map<String, Circle> idcircleMap = new HashMap<>();//表示当前的marker的经纬度是否为LBS  是否要画圈




    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        slideIns = this;
        EventBus.getDefault().register(MainActivity.this);
        token = PreferenceUtil.getString("token", "");
        Log.e("token", token);
        uri = URI.create("ws://f.super-gps.net/wssend/"+token);

        context = MainActivity.this;

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            //  getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);

        }


        if (NavigationBarUtil.hasNavigationBar(this)) {
            NavigationBarUtil.initActivity(findViewById(android.R.id.content));//解决底部适配
        }


        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerlayout);
        mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
        left_drawerlayout = (RelativeLayout) findViewById(R.id.main_left_drawer_layout);
        jianshi = (View) findViewById(R.id.jianshi);
        tv_lat = (TextView) findViewById(R.id.tv_lat);
        tv_lng = (TextView) findViewById(R.id.tv_lng);
        tv_speed = (TextView) findViewById(R.id.tv_speed);
        tv_voltage = (TextView) findViewById(R.id.tv_voltage);
        tv_carNumber = (TextView) findViewById(R.id.tv_carNumber);
        tv_time = (TextView) findViewById(R.id.tv_time);
        tv_carid = (TextView) findViewById(R.id.tv_carid);


        //获取地图控件引用
        mMapView = (MapView) findViewById(R.id.map);
        //在activity执行onCreate时执行mMapView.onCreate(savedInstanceState)，创建地图
        mMapView.onCreate(savedInstanceState);


        if (aMap == null) {
            aMap = mMapView.getMap();


        }
        aMap.moveCamera(CameraUpdateFactory.zoomTo(17));

        MyLocationStyle myLocationStyle = new MyLocationStyle();
        // 自定义定位蓝点图标
        // 自定义精度范围的圆形边框颜色
        myLocationStyle.strokeColor(Color.argb(0, 0, 0, 0));
        // 自定义精度范围的圆形边框宽度
        myLocationStyle.strokeWidth(0);
        myLocationStyle.myLocationIcon(BitmapDescriptorFactory.fromResource(R.mipmap.gps_point));
        // 设置圆形的填充颜色
        myLocationStyle.radiusFillColor(Color.argb(0, 0, 0, 0));
        // 将自定义的 myLocationStyle 对象添加到地图上
        aMap.setMyLocationStyle(myLocationStyle);
        aMap.setMyLocationEnabled(true);// 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
        // 设置定位的类型为定位模式 ，可以由定位、跟随或地图根据面向方向旋转几种
        aMap.setMyLocationType(AMap.LOCATION_TYPE_LOCATE);

        mUiSettings = aMap.getUiSettings();//实例化UiSettings类对象
        mUiSettings.setZoomControlsEnabled(false);
        mUiSettings.setCompassEnabled(false);
        mUiSettings.setScaleControlsEnabled(false);
        mUiSettings.setRotateGesturesEnabled(false);
        mUiSettings.setTiltGesturesEnabled(false);


        ///////////////地图缩放事件的监听//////
        aMap.setOnCameraChangeListener(new AMap.OnCameraChangeListener() {
            @Override
            public void onCameraChange(CameraPosition cameraPosition) {

            }

            @Override
            public void onCameraChangeFinish(CameraPosition cameraPosition) {
                if (cameraPosition.zoom <= 9) {
                    //Toast.makeText(MainActivity.this,String.valueOf(cameraPosition.zoom),Toast.LENGTH_LONG).show();
                }
            }
        });


        //地图的点击事件
        aMap.setOnMapClickListener(new AMap.OnMapClickListener() {
            @Override
            public void onMapClick(LatLng latLng) {
                if (flag_map_click == 1) {

                    flag_map_click = 0;
                }
                else {
                    carid = "no";
                    jianshi.setVisibility(View.GONE);
                }
                Log.e("点击地图","1");


            }
        });
        //标记点点击事件
        AMap.OnMarkerClickListener markerClickListener = new AMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker marker) {
                Log.e("点击标记","1");
                if (idmarkerMap != null && idmarkerMap.size() != 0) {
//                    final int finalI = i;
                    Iterator entries = idmarkerMap.entrySet().iterator();
                    boolean ishavemarker = false;
                    while (entries.hasNext()) {
                        Map.Entry entry = (Map.Entry) entries.next();
                        String key = (String) entry.getKey(); //目前是J-20的飞机航线有点问题，向下跳动不正确
                        Marker value = (Marker) entry.getValue();
                        if (value.getId().equals(marker.getId())) {
                            if (!key.equals(carid)) {
                                carid = key;
                                flag_map_click = 1;
                                get_ChePai();


                            }
                        }
                    }
                }


                return false;
            }
        };
        aMap.setOnMarkerClickListener(markerClickListener);

        quanxian();



        mHandler.postDelayed(r, 300000);//延时100毫秒

    }

    Handler mHandler = new Handler();
    Runnable r = new Runnable() {

        @Override
        public void run() {
            //do something
            //每隔1s循环执行run方法
            update_marker_circle();
            mHandler.postDelayed(this, 300000);
        }
    };
    public void update_marker_circle(){
        //5分钟访问一下接口 把离线的车的marker隐藏
        try {
            String url = getString(R.string.url) + "/device/index";

            OkHttpUtils.get(url)
                    .connTimeOut(10000)
                    .params("token",token)
                    .execute(new StringCallback() {
                        @Override
                        public void onSuccess(String s, Call call, Response response) {
                            MyLoading.cancel();
                            Object object = null;
                            object = JsonUtil.jsonParse(s);
                            if(object instanceof HashMap) {
                                final HashMap hashMap = (HashMap) object;
                                if (hashMap.containsKey("err")) ;
                                int err = Integer.valueOf(hashMap.get("err").toString());
                                if (err == 0) {
                                    ArrayList lists = new ArrayList();
                                    lists = (ArrayList)hashMap.get("list");
                                    for (int i = 0; i < lists.size(); i++) {
                                        HashMap hashMap1 = (HashMap) lists.get(i);
                                        String pic = hashMap1.get("state").toString();
                                        String id = hashMap1.get("id").toString();
                                        if(pic.equals("0")){
                                            //代表离线
                                            Iterator entries = idmarkerMap.entrySet().iterator();
                                            boolean ishavemarker = false;
                                            while (entries.hasNext()) {
                                                Map.Entry entry = (Map.Entry) entries.next();
                                                String key = (String) entry.getKey();
                                                Marker value = (Marker) entry.getValue();
                                                if (key.equals(id)) {
                                                    value.setVisible(false);
                                                    Circle circle1 = idcircleMap.get(key);
                                                    circle1.setVisible(false);


                                                }

                                            }
                                        }

                                    }


                                }else if(err < 0){
                                    ReLogin.login(MainActivity.this);
                                }else {
                                    Toast.makeText(MainActivity.this,hashMap.get("msg").toString(),Toast.LENGTH_LONG).show();
                                }
                            }


                        }

                        @Override
                        public void onError(Call call, Response response, Exception e) {
                            MyLoading.cancel();
                            Toast.makeText(MainActivity.this, "连接服务器失败", Toast.LENGTH_LONG).show();
                            e.printStackTrace();
                        }
                    });

        }catch (Exception e) {
            MyLoading.cancel();
            e.printStackTrace();
        }
    }


    public void get_ChePai() {

        MyLoading.show(MainActivity.this);
        try {
            String url = getString(R.string.url) + "/device/info";

            OkHttpUtils.get(url)
                    .connTimeOut(10000)
                    .params("id", carid)
                    .params("token", token)
                    .execute(new StringCallback() {
                        @Override
                        public void onSuccess(String s, okhttp3.Call call, Response response) {
                            MyLoading.cancel();
                            Object object = null;
                            object = JsonUtil.jsonParse(s);
                            if (object instanceof HashMap) {
                                HashMap hashMap = (HashMap) object;
                                if (hashMap.containsKey("err")) ;
                                int err = Integer.valueOf(hashMap.get("err").toString());
                                if (err == 0) {
                                    //  Toast.makeText(Login.this,hashMap.get("token").toString(),Toast.LENGTH_SHORT).show();
                                    HashMap hashMap1 = (HashMap) hashMap.get("data");
                                    chepai = hashMap1.get("car_no").toString();
                                    tv_carid.setText("车牌" + chepai);
                                    jianshi.setVisibility(View.VISIBLE);
                                } else {
                                    Toast.makeText(MainActivity.this, hashMap.get("msg").toString(), Toast.LENGTH_SHORT).show();
                                }
                            }


                        }

                        @Override
                        public void onError(Call call, Response response, Exception e) {

                            MyLoading.cancel();
                            Toast.makeText(MainActivity.this, "连接服务器失败", Toast.LENGTH_LONG).show();
                            e.printStackTrace();
                        }
                    });
        } catch (Exception e) {
            MyLoading.cancel();
            Toast.makeText(MainActivity.this, "访问网络异常", Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        }

    }

    public void click_outLogin(View view){
        PreferenceUtil.put("token", "");
        startActivity(new Intent(MainActivity.this,LoginActivity.class));
        finish();
    }
    public void click_chache(View view){
        //实时查车
        mDrawerLayout.closeDrawers();
    }

    public void click_dianzi(View view){
        //电子围栏
        startActivity(new Intent(MainActivity.this,Zhalan.class));
    }

    public void click_shebei(View view){
        //设备管理
        startActivity(new Intent(MainActivity.this,SheBei.class));
    }

    public void click_guiji(View view){
        //轨迹回放
        startActivity(new Intent(MainActivity.this,HuiFangList.class));
    }

    public void click_licheng(View view){
        //里程统计
        startActivity(new Intent(MainActivity.this,LiCheng.class));
    }

    public void click_tingliu(View view){
        //停留列表
        startActivity(new Intent(MainActivity.this,TingLiu.class));
    }

    public void click_baojing(View view){
        //报警列表
        startActivity(new Intent(MainActivity.this,BaoJing.class));
    }

    public void click_huiyuan(View view) {
        mDrawerLayout.openDrawer(left_drawerlayout);

    }

    public void dingwei(View view) {
        LatLng latLng = new LatLng(aMap.getMyLocation().getLatitude(), aMap.getMyLocation().getLongitude());
        aMap.moveCamera(CameraUpdateFactory.changeLatLng(latLng));

    }

    public void liebiao(View view) {

        startActivity(new Intent(MainActivity.this,che_xing_xuan_ze.class));

    }


    public void sock1() {
        /*
        方法三
         */
        new Thread(new Runnable() {
            @Override
            public void run() {
                if (!isduanwangFlag) {
                    exampleClient = new ExampleClient(uri);
                    exampleClient.setConnectionLostTimeout(0);
                    exampleClient.startSoc(exampleClient);
                } else {
                    exampleClient.reconnect(); //这里有点问题,断网后的重连
                }

            }
        }).start();

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void Event(Carsbeen carsbeen) {
        Log.e("信息", carsbeen.getId()+"  "+String.valueOf(carsbeen.getType())+"  "+String.valueOf(carsbeen.getWeidu()
        +"  "+String.valueOf(carsbeen.getJingdu()))+"  "+String
        .valueOf(carsbeen.getDianya())+"  "+ String.valueOf(carsbeen.getSudu()));
        //flag_map_click = 0;
        if(carsbeen.getType()!= 999) {
            get_MarkerLogo(carsbeen);

            if (carsbeen.getId().equals(carid)) {
                //点击了车

                if (carsbeen.getWeidu() == 999.0) {
                    tv_lat.setText("暂无");
                    tv_lng.setText("暂无");
                } else {

                    tv_lat.setText(String.format("%.4f", carsbeen.getWeidu()));
                    tv_lng.setText(String.format("%.4f", carsbeen.getJingdu()));
                }

                if (carsbeen.getDianya() < 0) {
                    tv_voltage.setText("暂无");
                } else {
                    tv_voltage.setText(String.valueOf(carsbeen.getDianya()));
                }

                if (carsbeen.getSudu() < 0) {
                    tv_speed.setText("暂无");
                } else {
                    double speed = (double) (carsbeen.getSudu() * 1.852);
                    tv_speed.setText(String.format("%.2f", speed)+"km");
                }

                tv_carNumber.setText(carsbeen.getId());
                tv_time.setText(DateUtil.getCurDate("MM月dd日 HH:mm"));
                if (chepai.length() != 0) {
                    tv_carid.setText("车牌" + chepai);
                }


            }
        }else {
            //选择车回来
            String id = carsbeen.getId();

            if (idmarkerMap != null && idmarkerMap.size() != 0) {
//                    final int finalI = i;
                Iterator entries = idmarkerMap.entrySet().iterator();
                boolean ishavemarker = false;
                while (entries.hasNext()) {
                    Map.Entry entry = (Map.Entry) entries.next();
                    String key = (String) entry.getKey(); //目前是J-20的飞机航线有点问题，向下跳动不正确
                    Marker value = (Marker) entry.getValue();
                        if (key.equals(id)) {
                            LatLng latLng = new LatLng(value.getPosition().latitude, value.getPosition().longitude);
                            aMap.moveCamera(CameraUpdateFactory.changeLatLng(latLng));


                        }

                }
            }

        }
    }


    //动态创建marker
    public void autoCreatMarker(Carsbeen carsbeen1,ImageView imageView) {


        markerOption = new MarkerOptions();
        latLng = new LatLng(carsbeen1.getWeidu(), carsbeen1.getJingdu());
        CoordinateConverter converter = new CoordinateConverter(MainActivity.this);
// CoordType.GPS 待转换坐标类型
        converter.from(CoordinateConverter.CoordType.GPS);
// sourceLatLng待转换坐标点 LatLng类型
        converter.coord(latLng);
// 执行转换操作
        LatLng desLatLng = converter.convert();
        markerOption.position(desLatLng);
        markerOption.draggable(false);//设置Marker可拖动
        // 将Marker设置为贴地显示，可以双指下拉地图查看效果
//        if(carsbeen1.getType() == 1 ){
//            markerOption.icon(BitmapDescriptorFactory.fromResource(R.mipmap.car));
//
//        }
//        else {
//            markerOption.icon(BitmapDescriptorFactory.fromResource(R.mipmap.car_0));
//        }

        markerOption.icon(BitmapDescriptorFactory.fromView(imageView));


        markerOption.setFlat(true);//设置marker平贴地图效果
        markerOption.anchor(0.5f, 0.5f);


        //设置圆
        Circle circle = aMap.addCircle(new CircleOptions().
                center(desLatLng).
                radius(300).
                fillColor(Color.argb(20, 0, 0, 255)).
                strokeColor(Color.argb(0, 0, 0, 255)).
                strokeWidth(0));
        circle.setVisible(false);


        if (idmarkerMap != null && idmarkerMap.size() != 0) {
            Iterator entries = idmarkerMap.entrySet().iterator();
            boolean ishavemarker = false;
            while (entries.hasNext()) {
                Map.Entry entry = (Map.Entry) entries.next();
                String key = (String) entry.getKey(); //
                Marker value = (Marker) entry.getValue();
                if (key.equals(carsbeen1.getId())) {
                    if(carsbeen1.getType() == 1 ){
                   //     value.setIcon(BitmapDescriptorFactory.fromResource(R.mipmap.car));
                    }
                    value.setVisible(true);
                    value.setPosition(desLatLng);    //

                    Circle circle1 = idcircleMap.get(key);
                    circle1.setCenter(desLatLng);
                    if (carsbeen1.getType() == 2) {
                        circle1.setVisible(true);
                    } else {
                        circle1.setVisible(false);
                    }

                    ishavemarker = true;
                    break;
                }
            }
            if (!ishavemarker) { //如果还没有被加进去，就把新的marker加到地图
                Marker marker = aMap.addMarker(markerOption);
                marker.setVisible(true);
                idmarkerMap.put(carsbeen1.getId(), marker);
                idcircleMap.put(carsbeen1.getId(), circle);
                if (carsbeen1.getType() == 2) {
                    circle.setVisible(true);
                }
                //carid = carsbeen1.getId();
            }
        } else if (idmarkerMap.size() == 0) { //如果还没有被加进去，就把新的marker加到地图
            Marker marker = aMap.addMarker(markerOption);
            marker.setVisible(true);
            idmarkerMap.put(carsbeen1.getId(), marker);
            idcircleMap.put(carsbeen1.getId(), circle);
            if (carsbeen1.getType() == 2) {
                circle.setVisible(true);
            }
            //carid = carsbeen1.getId();
        }


    }

    public void get_MarkerLogo(final Carsbeen carsbeen){

        try {
            final String url = getString(R.string.url) + "/device/info";

            OkHttpUtils.get(url)
                    .connTimeOut(10000)
                    .params("token", token)
                    .params("id", carsbeen.getId())
                    .execute(new StringCallback() {
                        @Override
                        public void onSuccess(String s, okhttp3.Call call, Response response) {
                            MyLoading.cancel();
                            Object object = null;
                            object = JsonUtil.jsonParse(s);
                            if (object instanceof HashMap) {
                                HashMap hashMap = (HashMap) object;
                                if (hashMap.containsKey("err")) ;
                                int err = Integer.valueOf(hashMap.get("err").toString());
                                if (err == 0) {
                                    final HashMap hashMap1 = (HashMap) hashMap.get("data");

                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            Glide.with(context)
                                                    .asBitmap()
                                                    .load(hashMap1.get("url").toString())
                                                    .into(new SimpleTarget<Bitmap>() {
                                                        @Override
                                                        public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {

                                                            ImageView imageView = new ImageView(MainActivity.this);

                                                            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(80,
                                                                    80);//两个50分别为添加图片的大小
                                                            imageView.setLayoutParams(params);
                                                            imageView.setImageBitmap(resource);

                                                            autoCreatMarker(carsbeen,imageView);
                                                        }

                                                    });
                                        }
                                    });


//                                            Bitmap bmp = null;
//                                            ImageView imageView = new ImageView(MainActivity.this);
//
//                                            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(50,
//                                                    50);//两个50分别为添加图片的大小
//                                            imageView.setLayoutParams(params);
//                                            try {
//                                                bmp = Glide.with(MainActivity.this).asBitmap().load("http://cdn.super-gps.net/clw/default_car1.png").submit().get();
//                                            } catch (InterruptedException e) {
//                                                e.printStackTrace();
//                                            } catch (ExecutionException e) {
//                                                e.printStackTrace();
//                                            }
//                                            imageView.setImageBitmap(bmp);
//                                            markerOption.icon(BitmapDescriptorFactory.fromView(imageView));

                                } else {
                                    Toast.makeText(context, hashMap.get("msg").toString(), Toast.LENGTH_SHORT).show();
                                }
                            }


                        }

                        @Override
                        public void onError(Call call, Response response, Exception e) {

                            MyLoading.cancel();
                            Toast.makeText(context, "连接服务器失败", Toast.LENGTH_LONG).show();
                            e.printStackTrace();
                        }
                    });
        } catch (Exception e) {
            MyLoading.cancel();
            Toast.makeText(context, "登录失败", Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        }


    }
    public boolean isWifiConnected(Context context) {//判读wifi是否可用
        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mWiFiNetworkInfo = mConnectivityManager
                    .getNetworkInfo(ConnectivityManager.TYPE_WIFI);
            if (mWiFiNetworkInfo != null) {
                return mWiFiNetworkInfo.isAvailable();
            }
        }
        return false;
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        //在activity执行onDestroy时执行mMapView.onDestroy()，销毁地图
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
        if(mMapView!=null) {
            mMapView.onDestroy();
        }
        if(exampleClient!=null) {
            exampleClient.close();
            exampleClient = null;
        }

    }

    @Override
    protected void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView.onResume ()，重新绘制加载地图
        isyouwang = isNetworkConnected(MainActivity.this) || isWifiConnected(MainActivity.this);
        if (isyouwang && !isduanwangFlag) {
            sock1();

        } else if (isyouwang && isduanwangFlag) {
            if (exampleClient != null) {
                exampleClient.close();
                exampleClient = null;
            }
            if (exampleClient == null) {
                sock1();

            }
        } else if (!isyouwang) {
            isduanwangFlag = true;
        }

        mMapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView.onPause ()，暂停地图的绘制
        mMapView.onPause();
        exampleClient.close();
        exampleClient = null;

    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        //在activity执行onSaveInstanceState时执行mMapView.onSaveInstanceState (outState)，保存地图当前的状态
        mMapView.onSaveInstanceState(outState);
    }


    public void quanxian(){
        lm = (LocationManager) MainActivity.this.getSystemService(MainActivity.this.LOCATION_SERVICE);
        boolean ok = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
//        if (ok) {//开了定位服务
        if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {
            Log.e("BRG","没有权限");
            // 没有权限，申请权限。
            // 申请授权。
            ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, LOCATION_CODE);
//                        Toast.makeText(getActivity(), "没有权限", Toast.LENGTH_SHORT).show();

        } else {

            // 有权限了，去放肆吧。
//                        Toast.makeText(getActivity(), "有权限", Toast.LENGTH_SHORT).show();
        }
//        } else {
        //去打开定位服务   这里用的网络定位  不需要gps
//            Log.e("BRG","系统检测到未开启GPS定位服务");
//            Toast.makeText(MainActivity.this, "系统检测到未开启GPS定位服务", Toast.LENGTH_SHORT).show();
//            Intent intent = new Intent();
//            intent.setAction(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
//            startActivityForResult(intent, 1315);
        //       }
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case LOCATION_CODE: {
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 权限被用户同意。
                    MyLocationStyle myLocationStyle;
                    myLocationStyle = new MyLocationStyle();//初始化定位蓝点样式类myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE);//连续定位、且将视角移动到地图中心点，定位点依照设备方向旋转，并且会跟随设备移动。（1秒1次定位）如果不设置myLocationType，默认也会执行此种模式。
                    myLocationStyle.interval(2000); //设置连续定位模式下的定位间隔，只在连续定位模式下生效，单次定位模式下不会生效。单位为毫秒。
                    myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATE);//只定位一次 显示到地图中心点
                    aMap.setMyLocationStyle(myLocationStyle);//设置定位蓝点的Style
//aMap.getUiSettings().setMyLocationButtonEnabled(true);//设置默认定位按钮是否显示，非必需设置。
                    aMap.setMyLocationEnabled(true);// 设置为true表示启动显示定位蓝点，false表示隐藏定位蓝点并不进行定位，默认是false。




                } else {
                    // 权限被用户拒绝了。
                    Toast.makeText(MainActivity.this, "定位权限被禁止，相关地图功能无法使用！",Toast.LENGTH_LONG).show();
                }

            }
        }
    }


}
